package com.example.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.commons.core.domain.BaseResponse;
import com.example.commons.core.entity.Role;
import com.example.commons.core.vo.receive.AddRoleReceiveVo;
import com.example.commons.core.vo.receive.RoleReceiveVo;
import com.example.commons.core.vo.result.RoleMenuResultVo;
import com.example.system.api.service.SystemMenuDubboService;
import com.example.user.service.RoleService;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RestController
@Log4j2
@RequestMapping("systemRole")
public class RoleController {
    private final RoleService roleService;
    @DubboReference
    private SystemMenuDubboService systemMenuDubboService;
    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 获取角色列表
     *
     * @return 角色列表
     */
    @GetMapping("getPage")
    public BaseResponse<IPage<RoleMenuResultVo>> getPage(RoleReceiveVo roleReceiveVo) {
        IPage<RoleMenuResultVo> iPage = new Page<>(roleReceiveVo.getPageNum(), roleReceiveVo.getPageSize());
        return BaseResponse.ok(roleService.getRoleMenuPage(iPage,roleReceiveVo));
    }

    /**
     * 获取角色列表
     *
     * @return 角色列表
     */
    @GetMapping("getList")
    public BaseResponse<List<Role>> getList() {
        return BaseResponse.ok(roleService.list());
    }

    /**
     * 新增或修改角色
     *
     * @return 角色列表
     */
    @PostMapping("addOrUpdateRole")
    public BaseResponse<Void> addOrUpdateRole(@RequestBody AddRoleReceiveVo role) {
        Role existRole = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getRoleSign, role.getRoleSign()));
        if (existRole != null) {
            Assert.isTrue(Objects.equals(existRole.getId(), role.getId()), "已存在相同的角色标识，请更改后提交！");
        }
        roleService.saveOrUpdate(role);
        //添加角色与菜单的关联关系
        systemMenuDubboService.addOrUpdateRoleMenuRelation(role.getMenuPermissions(),role.getId());
        return BaseResponse.ok();
    }

    /**
     * 获取角色列表
     *
     * @return 角色列表
     */
    @DeleteMapping("delRole/{roleId}")
    public BaseResponse<List<Role>> delRole(@PathVariable Long roleId) {
        roleService.removeById(roleId);
        return BaseResponse.ok();
    }
}
